package com.plian.system.service.fa.nplcancelrecord;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.plian.Tools.*;
import com.plian.Tools.office.WordUtil;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.cache.UserCache;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.constant.yth.YthConstant;
import com.plian.system.dao.bt.baseinfo.BaseInfoDao;
import com.plian.system.dao.fa.nplcancelmaintain.NPLCancelMaintainDao;
import com.plian.system.dao.fa.nplcancelrecord.NPLCancelRecordDao;
import com.plian.system.dao.fa.nplcancelrecordsublia.NPLCancelRecordSubliADao;
import com.plian.system.dao.fa.nplcancelrecordsublib.NPLCancelRecordSubliBDao;
import com.plian.system.dao.fa.nplcancelrecordsublic.NPLCancelRecordSubliCDao;
import com.plian.system.dao.sys.orgzation.OrgzationDao;
import com.plian.system.dao.sys.user.UserDao;
import com.plian.system.dao.wf.WfCompletedTaskMapper;
import com.plian.system.entity.fa.nplcancelrecord.CqzcNplcancelrecord;
import com.plian.system.entity.fa.nplcancelrecord.CqzcNplcancelrecordsublia;
import com.plian.system.entity.fa.nplcancelrecord.CqzcNplcancelrecordsublib;
import com.plian.system.entity.fa.nplcancelrecord.CqzcNplcancelrecordsublic;
import com.plian.system.entity.sys.ApprovalMessage;
import com.plian.system.mapper.fa.nplcancelrecord.CqzcNplcancelrecordMapper;
import com.plian.system.model.*;
import com.plian.system.model.page.Page;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.properties.GzwProperties;
import com.plian.system.service.pm.property.PropertyService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.service.sys.message.IApprovalMessageService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.service.sys.user.ISysUserService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.pm.npl.AnnualCompanyStatisticalInfoVO;
import com.plian.system.vo.pm.npl.AnnualCompanyStatisticalVO;
import com.plian.system.vo.pm.npl.AnnualStatisticalDetailVO;
import com.plian.system.vo.pm.npl.AnnualStatisticalVO;
import com.plian.system.vo.yth.YthResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

import static com.plian.system.constant.sys.FormStatusConstant.*;
import static com.plian.system.constant.sys.FormTypeConstant.CQZC_NPL_CANCEL_RECORD;

@Slf4j
@Service
public class NPLCancelRecordService implements BaseFlowService {
    @Autowired
    NPLCancelRecordDao nPLCancelRecordDao;
    @Autowired
    NPLCancelRecordSubliADao nPLCancelRecordSubliADao;
    @Autowired
    NPLCancelRecordSubliBDao nPLCancelRecordSubliBDao;
    @Autowired
    NPLCancelRecordSubliCDao nPLCancelRecordSubliCDao;
    @Autowired
    OrgzationDao orgzationDao;
    @Autowired
    FileService fileService;
    @Autowired
    IFormCodeService formCodeService;
    @Autowired
    BaseInfoDao baseInfoDao;
    @Autowired
    @Lazy
    private FormWorkflowService formWorkflowService;
    @Autowired
    Environment environment;
    @Autowired
    WfCompletedTaskMapper wfCompletedTaskMapper;
    @Autowired
    UserDao userDao;
    @Autowired
    PropertyService propertyService;

    @Autowired
    NPLCancelMaintainDao nplCancelMaintainDao;

    @Autowired
    private IApprovalMessageService approvalMessageService;

    @Autowired
    private GzwProperties gzwProperties;

    @Autowired
    private ICqzcNplcancelrecordsubliaService nplcancelrecordsubliaService;

    @Autowired
    private ICqzcNplcancelrecordsublibService nplcancelrecordsublibService;

    @Autowired
    private ICqzcNplcancelrecordsublicService nplcancelrecordsublicService;

    @Autowired
    private CqzcNplcancelrecordMapper nplcancelrecordMapper;

    @Autowired
    private IOrgService orgService;

    @Autowired
    private ISysUserService userService;


    /**
     * logger属性.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(NPLCancelRecordService.class);

    /**
     * 保存
     *
     * @param pd
     * @return
     */
    public ObjResult save(PageData pd) {
        try {
            pd.put("id", UuidUtil.get32UUID());
            pd.put("orgId", TokenUtil.getTokenOrgId());
            pd.put("formType", FormTypeConstant.CQZC_NPL_CANCEL_RECORD);
            pd.put("createUser", TokenUtil.getTokenUserId());
            pd.put("createTime", new Date());
            pd.put("updateUser", TokenUtil.getTokenUserId());
            pd.put("updateTime", new Date());
            pd.put("code", formCodeService.getCode(FormTypeConstant.CQZC_NPL_CANCEL_RECORD));
            nPLCancelRecordDao.save(pd);
            fileService.edit(pd.getString("id"), (List<HashMap>) pd.get("list_doc"));
            ObjectMapper mapper = new ObjectMapper();
            List<PageData> listSubliA = mapper.convertValue((List<PageData>) pd.get("listSubliA"),
                    new TypeReference<List<PageData>>() {
                    });

            List<PageData> listSubliB = mapper.convertValue((List<PageData>) pd.get("listSubliB"),
                    new TypeReference<List<PageData>>() {
                    });

            List<PageData> listSubliC = mapper.convertValue((List<PageData>) pd.get("listSubliC"),
                    new TypeReference<List<PageData>>() {
                    });
            if (listSubliA != null && listSubliA.size() > 0) {
                saveSubli(listSubliA, pd.getString("id"), "A");
            }
            if (listSubliB != null && listSubliB.size() > 0) {
                saveSubli(listSubliB, pd.getString("id"), "B");
            }
            if (listSubliC != null && listSubliC.size() > 0) {
                saveSubli(listSubliC, pd.getString("id"), "C");
            }

            HashMap<String, Object> processVariable = new HashMap<>();
            formWorkflowService.startProcessAndSimulate(pd.getString("id"), pd.getString("formType"), processVariable);
            return new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
    }

    /**
     * saveOrUpdate
     *
     * @param nplcancelrecord
     * @return
     */
    public ObjResult save(CqzcNplcancelrecord nplcancelrecord) {

        try {
            String uuid = null;
            if (StringUtil.isBlank(nplcancelrecord.getId())) {
                uuid = UuidUtil.get32UUID();
                nplcancelrecord.setId(uuid);
                if (StringUtils.isEmpty(nplcancelrecord.getOrgId())) {
                    nplcancelrecord.setOrgId(TokenUtil.getTokenOrgId());
                }
                nplcancelrecord.setStatus(String.valueOf(FormStatusConstant.UNREVIEWED));
                nplcancelrecord.setFormType(String.valueOf(FormTypeConstant.CQZC_NPL_CANCEL_RECORD));
                nplcancelrecord.setCreateTime(new Date());
                nplcancelrecord.setCode(formCodeService.getCode(FormTypeConstant.CQZC_NPL_CANCEL_RECORD));
                nplcancelrecordMapper.insert(nplcancelrecord);
                fileService.saveAll(uuid, nplcancelrecord.getList_doc());

            } else {
                uuid = nplcancelrecord.getId();
                nplcancelrecord.setUpdateTime(new Date());
                nplcancelrecordMapper.updateById(nplcancelrecord);
                fileService.edit(uuid, nplcancelrecord.getList_doc());
                //del
                nPLCancelRecordSubliADao.delByParent(uuid);
                nPLCancelRecordSubliBDao.delByParent(uuid);
                nPLCancelRecordSubliCDao.delByParent(uuid);
            }
            if (StringUtil.isNotBlank(nplcancelrecord.getAttachIds())) {
                fileService.upYthFile(nplcancelrecord.getAttachIds(), nplcancelrecord.getId());
            }
            List<CqzcNplcancelrecordsublia> listSubliA = nplcancelrecord.getListSubliA();
            List<CqzcNplcancelrecordsublib> listSubliB = nplcancelrecord.getListSubliB();
            List<CqzcNplcancelrecordsublic> listSubliC = nplcancelrecord.getListSubliC();

            if (listSubliA != null && listSubliA.size() > 0) {
                saveSubliA(listSubliA, uuid);
            }
            if (listSubliB != null && listSubliB.size() > 0) {
                saveSubliB(listSubliB, uuid);
            }
            if (listSubliC != null && listSubliC.size() > 0) {
                saveSubliC(listSubliC, uuid);
            }
            return new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }

    }


    /**
     * 修改
     *
     * @param pd
     * @return
     */
    public ObjResult edit(PageData pd) {
        try {
            pd.put("updateUser", TokenUtil.getTokenUserId());
            pd.put("updateTime", new Date());
            pd.put("reportingTime", new Date());
            nPLCancelRecordDao.edit(pd);
            fileService.edit(pd.getString("id"), (List<HashMap>) pd.get("list_doc"));
            nPLCancelRecordSubliADao.delByParent(pd.getString("id"));
            nPLCancelRecordSubliBDao.delByParent(pd.getString("id"));
            nPLCancelRecordSubliCDao.delByParent(pd.getString("id"));
            ObjectMapper mapper = new ObjectMapper();
            List<PageData> listSubliA = mapper.convertValue((List<PageData>) pd.get("listSubliA"),
                    new TypeReference<List<PageData>>() {
                    });

            List<PageData> listSubliB = mapper.convertValue((List<PageData>) pd.get("listSubliB"),
                    new TypeReference<List<PageData>>() {
                    });

            List<PageData> listSubliC = mapper.convertValue((List<PageData>) pd.get("listSubliC"),
                    new TypeReference<List<PageData>>() {
                    });
            if (listSubliA != null && listSubliA.size() > 0) {
                saveSubli(listSubliA, pd.getString("id"), "A");
            }
            if (listSubliB != null && listSubliB.size() > 0) {
                saveSubli(listSubliB, pd.getString("id"), "B");
            }
            if (listSubliC != null && listSubliC.size() > 0) {
                saveSubli(listSubliC, pd.getString("id"), "C");
            }
            return new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
    }

    /**
     * 保存从表
     *
     * @param list
     * @param nplcancelrecordId
     * @throws Exception
     */
    public void saveSubli(List<PageData> list, String nplcancelrecordId, String Key) throws Exception {
        if (list != null && list.size() > 0) {
            for (PageData pageData : list) {
                pageData.put("nplcancelrecordId", nplcancelrecordId);
                pageData.put("id", UuidUtil.get32UUID());
            }
            switch (Key) {
                case "A":
                    nPLCancelRecordSubliADao.saveAll(list);
                    break;
                case "B":
                    nPLCancelRecordSubliBDao.saveAll(list);
                    break;
                case "C":
                    nPLCancelRecordSubliCDao.saveAll(list);
                    break;
            }
        }
    }

    /**
     * @param list
     * @param nplcancelrecordId
     * @throws Exception
     */
    public void saveSubliA(List<CqzcNplcancelrecordsublia> list, String nplcancelrecordId) throws Exception {
        if (list != null && list.size() > 0) {
            for (CqzcNplcancelrecordsublia pageData : list) {
                if (StringUtil.isBlank(pageData.getId())) {
                    pageData.setNplcancelrecordId(nplcancelrecordId);
                    pageData.setId(UuidUtil.get32UUID());
                }
            }
            nplcancelrecordsubliaService.saveOrUpdateBatch(list);
        }
    }

    /**
     * @param list
     * @param nplcancelrecordId
     * @throws Exception
     */
    public void saveSubliB(List<CqzcNplcancelrecordsublib> list, String nplcancelrecordId) throws Exception {
        if (list != null && list.size() > 0) {
            for (CqzcNplcancelrecordsublib pageData : list) {
                if (StringUtil.isBlank(pageData.getId())) {
                    pageData.setNplcancelrecordId(nplcancelrecordId);
                    pageData.setId(UuidUtil.get32UUID());
                }
            }
            nplcancelrecordsublibService.saveOrUpdateBatch(list);
        }
    }

    /**
     * @param list
     * @param nplcancelrecordId
     * @throws Exception
     */
    public void saveSubliC(List<CqzcNplcancelrecordsublic> list, String nplcancelrecordId) throws Exception {
        if (list != null && list.size() > 0) {
            for (CqzcNplcancelrecordsublic pageData : list) {
                if (StringUtil.isBlank(pageData.getId())) {
                    pageData.setNplcancelrecordId(nplcancelrecordId);
                    pageData.setId(UuidUtil.get32UUID());
                }
            }
            nplcancelrecordsublicService.saveOrUpdateBatch(list);
        }
    }

    /**
     * 单据详情
     *
     * @param pd
     * @return
     */
    public ObjResult findbyid(PageData pd) {
        try {
            ObjResult objResult;
            PageData p = nPLCancelRecordDao.findById(pd.getString("id"));
            List<PageData> listSubliA = nPLCancelRecordSubliADao.findById(pd.getString("id"));
            List<PageData> listSubliB = nPLCancelRecordSubliBDao.findById(pd.getString("id"));
            List<PageData> listSubliC = nPLCancelRecordSubliCDao.findById(pd.getString("id"));
            p.put("listSubliA", listSubliA);
            p.put("listSubliB", listSubliB);
            p.put("listSubliC", listSubliC);
            objResult = new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
            return objResult;
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
    }

    /**
     * 根据id删除
     *
     * @param ids
     * @return
     */
    public ObjResult del_ids(List<String> ids) {
        try {
            nPLCancelRecordDao.del_ids(ids);
            for (String s : ids) {
                formWorkflowService.deleteProcessInstance(s);
            }
            return new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
    }

    /**
     * 查询列表
     *
     * @return
     */
    public ListResult list(PageData pd) {
        ListResult listResult;
        try {
            pd.put("orgId", TokenUtil.getTokenOrgId());
            String status = pd.getString("status");
            if (null != status && !"".equals(status)) {
                pd.put("status", status.trim());
            }
            Page page = new Page(true, pd);
            List<PageData> list = nPLCancelRecordDao.list(page);
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(list);
            listResult.setTotal(page.getTotal());
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            listResult = new ListResult(CommonCode.ERROR);
        }
        return listResult;
    }

    /**
     * 查询列表
     *
     * @return
     */
    public ListResult reportList(PageData pd) {
        ListResult listResult;
        try {
            Page page = new Page(true, pd);
            List<PageData> list = nPLCancelRecordDao.reportListPage(page);
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(list);
            listResult.setTotal(page.getTotal());
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            listResult = new ListResult(CommonCode.ERROR);
        }
        return listResult;
    }


    public List<AnnualStatisticalVO> annualStatisticalOrderByRecordCode(PageData pd) {
        List<AnnualStatisticalVO> results = new ArrayList<>();
        try {
            results = nPLCancelRecordDao.annualStatisticalOrderByRecordCode(pd);
            if (CollectionUtil.isNotEmpty(results)) {
                AnnualStatisticalVO sumVO = new AnnualStatisticalVO();
                sumVO.setRecordCode("合计");
                BigDecimal sumAmount = new BigDecimal(0);
                for (AnnualStatisticalVO statisticalVO : results) {
                    sumAmount = BigDecimalUtil.add(BigDecimalUtil.toBigdecimal(statisticalVO.getAmount()), sumAmount);
                }
                sumVO.setAmount(BigDecimalUtil.toPlanString(sumAmount));
                results.add(sumVO);
            }
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
        }
        return results;
    }

    public R<List<AnnualStatisticalDetailVO>> annualStatisticalDetail(PageData pd) {
        R<List<AnnualStatisticalDetailVO>> r;
        try {
            List<AnnualStatisticalDetailVO> results;
            String formType = pd.getString("formType");
            String id = pd.getString("id");

            if (StringUtil.isBlank(id)) {
                return new R(CustomCode.builder().message("单据id为空").code(1999).success(false).build());
            }

            if (StringUtil.isBlank(formType)) {
                return new R(CustomCode.builder().message("单据类型为空").code(1999).success(false).build());
            }

            if (String.valueOf(FormTypeConstant.CQZC_NPL_CANCEL_RECORD).equals(formType)) {
                results = nPLCancelRecordDao.annualStatisticalDetailById(id);
            } else if (String.valueOf(FormTypeConstant.CQZC_NPL_CANCEL_MAINTAIN).equals(formType)) {
                results = nplCancelMaintainDao.annualStatisticalDetailById(id);
            } else {
                return new R(CustomCode.builder().message("单据类型错误").code(1999).success(false).build());
            }

            r = new R<>(CommonCode.SUCCESS);
            r.setPageData(results);

        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            return new R<>(CommonCode.ERROR);
        }
        return r;
    }

    public List<AnnualCompanyStatisticalVO> annualStatisticalGroupByCompany(PageData pd) {
        List<AnnualCompanyStatisticalVO> results = new ArrayList<>();
        try {
            results = nPLCancelRecordDao.annualStatisticalGroupByCompany(pd);
            if (CollectionUtil.isEmpty(results)) {
                return results;
            }
            List<AnnualCompanyStatisticalVO> tempList = new ArrayList<>();
            tempList.addAll(results);
            AnnualCompanyStatisticalVO total = AnnualCompanyStatisticalVO.builder().orgName("合计").isSummary(2).build();
            AnnualCompanyStatisticalInfoVO totalInfo = new AnnualCompanyStatisticalInfoVO();
            totalInfo.setAmount(new BigDecimal(0));
            List<AnnualCompanyStatisticalInfoVO> totalChildren = new ArrayList<>();
            totalChildren.add(totalInfo);
            total.setChildren(totalChildren);

            int count = 1;
            for (int i = 0; i < tempList.size(); i++) {
                AnnualCompanyStatisticalVO result = tempList.get(i);
                AnnualCompanyStatisticalVO subTotal = AnnualCompanyStatisticalVO.builder().orgName("小计").isSummary(2).build();
                AnnualCompanyStatisticalInfoVO subTotalInfo = new AnnualCompanyStatisticalInfoVO();
                List<AnnualCompanyStatisticalInfoVO> childInfos = result.getChildren();
                subTotalInfo.setAmount(childInfos.stream()
                        .map(AnnualCompanyStatisticalInfoVO::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
                List<AnnualCompanyStatisticalInfoVO> children = new ArrayList<>();
                children.add(subTotalInfo);
                subTotal.setChildren(children);
                results.add(i + count, subTotal);
                count += 1;
                totalInfo.setAmount(BigDecimalUtil.add(totalInfo.getAmount(), subTotalInfo.getAmount()));
            }

            results.add(total);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
        }
        return results;
    }

    /**
     * 提交
     *
     * @param ids
     * @return
     */
    public HashMap<String, Object> commit(String ids){
        PageData pageData = new PageData();
        pageData.put("status", String.valueOf(FLOW));
        List<String> strings = new ArrayList<>();
        strings.add(ids);
        pageData.put("id", strings);
        try {
            nPLCancelRecordDao.refer(pageData);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException("上报失败");
        }
        return new HashMap<String, Object>();
    }

    /**
     * 退回单据
     *
     * @param formId 单据id
     */
    public Boolean reject(String formId, int formState, String comment){
        PageData pageData = new PageData();
        pageData.put("status", String.valueOf(formState));
        pageData.put("id", Collections.singletonList(formId));

        CqzcNplcancelrecord nplcancelrecord = nplcancelrecordMapper.selectOne(Wrappers.<CqzcNplcancelrecord>lambdaQuery().eq(CqzcNplcancelrecord::getId, formId));
        if (Optional.ofNullable(nplcancelrecord).isPresent()) {
            if (YthConstant.DATA_NINGBO.equals(nplcancelrecord.getDataSource())) {
                ApprovalMessage approvalMessage = new ApprovalMessage();
                approvalMessage.setDataSourceId(nplcancelrecord.getDataSourceId());
                approvalMessage.setOpinion(comment);
                approvalMessage.setIsApprove(1);
                approvalMessage.setIsSend(1);
                approvalMessage.setDataSourceType(YthConstant.DATA_NINGBO);
                approvalMessage.setFilingUserName(UserCache.userIdToName(TokenUtil.getTokenUserId()));
                approvalMessage.setFormType(Integer.valueOf(nplcancelrecord.getFormType()));
                approvalMessageService.save(approvalMessage);
            }
        }
        try {
            nPLCancelRecordDao.refer(pageData);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException("回退失败");
        }
        return true;
    }

    /**
     * 审批完成
     *
     * @param formId
     */
    public Boolean finish(String formId) {
        try {
            PageData pageData = nPLCancelRecordDao.findById(formId);
            pageData.put("status", String.valueOf(FINISH));
            String code = formCodeService.getFilingCode(FormTypeConstant.CQZC_NPL_CANCEL_RECORD);
            pageData.put("recordCode", gzwProperties.getCodeStartName() + "核备〔" + code.substring(0, 4) + "〕（" + code.substring(code.length() - 3, code.length()) + "）号");

            CqzcNplcancelrecord nplcancelrecord = nplcancelrecordMapper.selectOne(Wrappers.<CqzcNplcancelrecord>lambdaQuery().eq(CqzcNplcancelrecord::getId, formId));
            if (Optional.ofNullable(nplcancelrecord).isPresent()) {
                if (YthConstant.DATA_NINGBO.equals(nplcancelrecord.getDataSource())) {
                    ApprovalMessage approvalMessage = new ApprovalMessage();
                    approvalMessage.setDataSourceId(nplcancelrecord.getDataSourceId());
                    approvalMessage.setOpinion("审批通过");
                    approvalMessage.setIsApprove(2);
                    approvalMessage.setIsSend(1);
                    approvalMessage.setDataSourceType(YthConstant.DATA_NINGBO);
                    approvalMessage.setFilingUserName(UserCache.userIdToName(TokenUtil.getTokenUserId()));
                    approvalMessage.setFormType(Integer.valueOf(nplcancelrecord.getFormType()));
                    approvalMessage.setFilingCode(nplcancelrecord.getCode());
                    approvalMessageService.save(approvalMessage);
                }
            }
            nPLCancelRecordDao.edit(pageData);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            throw new MyRuntimeException("单据流转完成时修改单据状态失败！");
        }
        return true;
    }

    /**
     * 工作流
     *
     * @param formIds 单据ids
     */
    public List<PageData> findByIds(List<String> formIds) {
        try {
            PageData pageData = new PageData();
            pageData.put("ids", formIds);
            List<PageData> byIds = nPLCancelRecordDao.findByIds(pageData);
            List<PageData> pageData1 = new ArrayList<>();
            for (PageData pd : byIds) {
                String unitname = pd.getString("UNITNAME");
                pd.put("orgName", unitname);
                pageData1.add(pd);
            }
            return pageData1;
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            throw new MyRuntimeException("根据单据id列表查询报表失败！");
        }
    }

    @Override
    public List<Integer> getFormType() {
        return Arrays.asList(CQZC_NPL_CANCEL_RECORD);
    }

    /**
     * 回到经办人
     *
     * @param formId
     */
    public void goBackToStash(String formId) {
        try {
            PageData pageData = new PageData();
            pageData.put("status", String.valueOf(UNREVIEWED));
            pageData.put("id", Collections.singletonList(formId));
            nPLCancelRecordDao.refer(pageData);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
        }
    }

    public File createReceptFile(String id) throws Exception {
        PageData pd = nPLCancelRecordDao.findById(id);
        List<PageData> listSubliA = nPLCancelRecordSubliADao.findById(id);
        List<PageData> listSubliB = nPLCancelRecordSubliBDao.findById(id);
        List<PageData> listSubliC = nPLCancelRecordSubliCDao.findById(id);

        Document document = new Document(com.itextpdf.text.PageSize.A4, 10, 10, 30, 40);
        FileOutputStream fs;
        BaseFont bfHeiTi;
        BaseFont bfST;
        BaseFont test;
        BaseFont bfbt;
        File pdffile = File.createTempFile(id.toString(), ".pdf");
        if (pdffile.exists()) {
            pdffile.delete();
        }
        fs = new FileOutputStream(pdffile.getPath());//getAbsolutePath
        PdfWriter.getInstance(document, fs);
        document.open();
        bfST = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        bfHeiTi = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        bfbt = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        test = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        // 添加标题
        Font font_Biaoti = new Font(bfHeiTi, 20.0f, Font.BOLD, BaseColor.BLACK);
        Font font_biaotou1 = new Font(test, 12.0f, Font.NORMAL, BaseColor.BLACK);
        Font font_biaotou2 = new Font(bfbt, 10.0f, Font.NORMAL, BaseColor.BLACK);
        Font font_Zhengwen = new Font(bfST, 11.0f, Font.NORMAL, BaseColor.BLACK);
        // 创建一个段落
        String title = "市属企业不良资产核销事前备案表";
        Paragraph biaoti = new Paragraph(title, font_Biaoti);
        biaoti.setAlignment(1);
        biaoti.setSpacingAfter(20f);
        document.add(biaoti);
        // 创建副标题
        String recordCode = pd.getString("recordCode");
        if (recordCode == null) {
            recordCode = "";
        }
        String title1 = "备案编号:" + recordCode;
        title1 += "                  金额：万元 ";
        Paragraph biaoti1 = new Paragraph(title1, font_biaotou1);
        biaoti1.setAlignment(Element.ALIGN_CENTER);
        biaoti1.setSpacingAfter(10f);
        document.add(biaoti1);

        PdfPTable table = new PdfPTable(4);// 建立一个pdf表格
        table.setSpacingBefore(10f);// 设置表格上面空白宽度
        table.setSpacingAfter(0f);// 设置表格下面空白宽度
        table.setSpacingBefore(10f);// 设置表格上面空白宽度
        table.setSpacingAfter(0f);// 设置表格下面空白宽度
        table.setTotalWidth(800);// 设置表格的宽度

        PdfPCell cell = new PdfPCell(new Phrase("填报单位", font_Zhengwen));
        cell.setMinimumHeight(30);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell);
        PdfPCell cell2 = new PdfPCell(new Phrase(pd.getString("reportCompanyName"), font_Zhengwen));
        cell2.setColspan(3);
        cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell2);

        PdfPCell cell3 = new PdfPCell(new Phrase("资产核销企业性质", font_Zhengwen));
        cell3.setMinimumHeight(30);
        cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell3);

        String cancelType = pd.getString("cancelType");
        cancelType = baseInfoDao.findbycode(cancelType).getString("name");
        PdfPCell cell4 = new PdfPCell(new Phrase(cancelType, font_Zhengwen));
        cell4.setColspan(3);
        cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell4.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell4);

        PdfPCell cell5 = new PdfPCell(new Phrase("经济行为决策机构\n" +
                "及批准文件日期", font_Zhengwen));
        cell5.setMinimumHeight(30);
        cell5.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell5.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell5.setPaddingTop(5);
        cell5.setPaddingBottom(5);
        table.addCell(cell5);

        String approvalDate = pd.getString("approvalDate");
        String institutions = pd.getString("institutions");
        String ins = "";
        if (Tools.notEmpty(approvalDate)) {
            approvalDate = Tools.date2Str(Tools.str2Date(approvalDate), "yyyy-MM-dd");
            ins = "决策机构:" + institutions + "\n" + "批准日期:" + approvalDate;
        } else {
            ins = "决策机构:" + institutions;
        }

        PdfPCell cell6 = new PdfPCell(new Phrase(ins, font_Zhengwen));
        cell6.setColspan(3);
        cell6.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell6.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell6);
        PdfPCell cell7 = new PdfPCell(new Phrase("不良资产基本情况", font_Zhengwen));
        cell7.setColspan(4);
        cell7.setMinimumHeight(30);
        cell7.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell7.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell7);

        PdfPCell cell8 = new PdfPCell(new Phrase("核销不良资产内容", font_Zhengwen));
        cell8.setMinimumHeight(30);
        cell8.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell8.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell8);

        PdfPCell cell9 = new PdfPCell(new Phrase(pd.getString("cancelNote"), font_Zhengwen));
        cell9.setColspan(3);
        cell9.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell9.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell9);

        PdfPCell cell10 = new PdfPCell(new Phrase("核销不良资产总额\n（币种大小写金额）", font_Zhengwen));
        cell10.setMinimumHeight(30);
        cell10.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell10.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell10.setPaddingTop(5);
        cell10.setPaddingBottom(5);
        table.addCell(cell10);

        String currency = pd.getString("currency");
        currency = baseInfoDao.findbycode(currency).getString("name");
        String amount = pd.getString("amount");
        PdfPCell cell11 = new PdfPCell(new Phrase(currency + ":" + amount, font_Zhengwen));
        cell11.setMinimumHeight(30);
        cell11.setColspan(3);
        cell11.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell11.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell11);

        if (CollectionUtils.isNotEmpty(listSubliB)) {
            PageData pageData = listSubliB.get(0);
            String nplType = pageData.getString("nplType");
            if ("往来款项".equals(nplType)) {
                PdfPCell cell13 = new PdfPCell(new Phrase("往来款项类", font_Zhengwen));
                cell13.setMinimumHeight(30);
                cell13.setRowspan(listSubliB.size() + 1);
                cell13.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell13.setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cell13);
                String str2[] = {
                        "账面原值总额",
                        "坏账损失总额",
                        "账面净值总额",
                };
                String keys2[] = {
                        "totolOriginalBookValue",
                        "totolBadDebtLosses",
                        "totolOriginalNetValue",
                };
                for (int i = 0; i < str2.length; i++) {
                    String s = str2[i];
                    PdfPCell cell14 = new PdfPCell(new Phrase(s, font_Zhengwen));
                    cell14.setMinimumHeight(30);
                    cell14.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell14.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    table.addCell(cell14);
                }
                for (PageData p1 : listSubliB) {
                    for (int i = 0; i < keys2.length; i++) {
                        String key = keys2[i];
                        PdfPCell cell14 = new PdfPCell(new Phrase(p1.getString(key), font_Zhengwen));
                        cell14.setMinimumHeight(30);
                        cell14.setHorizontalAlignment(Element.ALIGN_CENTER);
                        cell14.setVerticalAlignment(Element.ALIGN_MIDDLE);
                        table.addCell(cell14);
                    }
                }
            }
        } else {
            PdfPCell cell13 = new PdfPCell(new Phrase("往来款项类", font_Zhengwen));
            cell13.setMinimumHeight(30);
            cell13.setRowspan(2);
            cell13.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell13.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell13);
            String str2[] = {
                    "账面原值总额",
                    "坏账损失总额",
                    "账面净值总额",
            };
            String keys2[] = {
                    "totolOriginalBookValue",
                    "totolBadDebtLosses",
                    "totolOriginalNetValue",
            };
            for (int i = 0; i < str2.length; i++) {
                String s = str2[i];
                PdfPCell cell14 = new PdfPCell(new Phrase(s, font_Zhengwen));
                cell14.setMinimumHeight(30);
                cell14.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell14.setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cell14);
            }
            for (int i = 0; i < keys2.length; i++) {
                PdfPCell cell14 = new PdfPCell(new Phrase("0", font_Zhengwen));
                cell14.setMinimumHeight(30);
                cell14.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell14.setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cell14);
            }
        }

        if (CollectionUtils.isNotEmpty(listSubliC)) {
            PageData pageData = listSubliC.get(0);
            String nplType = pageData.getString("nplType");
            if ("对外投资".equals(nplType)) {
                PdfPCell cell14 = new PdfPCell(new Phrase("投资类", font_Zhengwen));
                cell14.setMinimumHeight(30);
                cell14.setRowspan(listSubliC.size() + 1);
                cell14.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell14.setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cell14);

                String str3[] = {
                        "账面值",
                        "收回金额",
                        "投资损失总额",
                };
                String keys3[] = {
                        "totolOriginalBookValue",
                        "recoverTheAmount",
                        "totolInvestmentLoss",
                };
                for (int i = 0; i < str3.length; i++) {
                    String s = str3[i];
                    PdfPCell cell15 = new PdfPCell(new Phrase(s, font_Zhengwen));
                    cell15.setMinimumHeight(30);

                    cell15.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell15.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    table.addCell(cell15);
                }

                for (PageData p1 : listSubliC) {
                    for (int i = 0; i < keys3.length; i++) {
                        String key = keys3[i];
                        PdfPCell cell15 = new PdfPCell(new Phrase(p1.getString(key), font_Zhengwen));
                        cell15.setMinimumHeight(30);
                        cell15.setHorizontalAlignment(Element.ALIGN_CENTER);
                        cell15.setVerticalAlignment(Element.ALIGN_MIDDLE);
                        cell15.setPaddingTop(5);
                        cell15.setPaddingBottom(5);
                        table.addCell(cell15);
                    }
                }
            }
        } else {
            PdfPCell cell14 = new PdfPCell(new Phrase("投资类", font_Zhengwen));
            cell14.setMinimumHeight(30);
            cell14.setRowspan(2);
            cell14.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell14.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell14);

            String str3[] = {
                    "账面值",
                    "收回金额",
                    "投资损失总额",
            };
            String keys3[] = {
                    "totolOriginalBookValue",
                    "recoverTheAmount",
                    "totolInvestmentLoss",
            };
            for (int i = 0; i < str3.length; i++) {
                String s = str3[i];
                PdfPCell cell15 = new PdfPCell(new Phrase(s, font_Zhengwen));
                cell15.setMinimumHeight(30);

                cell15.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell15.setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cell15);
            }
            for (int i = 0; i < keys3.length; i++) {
                PdfPCell cell15 = new PdfPCell(new Phrase("0", font_Zhengwen));
                cell15.setMinimumHeight(30);
                cell15.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell15.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cell15.setPaddingTop(5);
                cell15.setPaddingBottom(5);
                table.addCell(cell15);
            }
        }

        if (CollectionUtils.isNotEmpty(listSubliA)) {
            PageData pageData = listSubliA.get(0);
            String nplType = pageData.getString("nplType");
            if ("存货".equals(nplType) || "待摊费用".equals(nplType) || "固定资产".equals(nplType) || "在建工程和工程物资".equals(nplType) || "无形资产和其他资产".equals(nplType)) {
                PdfPCell cell12 = new PdfPCell(new Phrase("实物资产类", font_Zhengwen));
                cell12.setMinimumHeight(30);
                cell12.setRowspan(listSubliA.size() + 1);
                cell12.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell12.setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cell12);
                String str1[] = {
                        "账面原值总额",
                        "累计折旧总额",
                        "账面净值总额",
                };
                String keys1[] = {
                        "totolOriginalBookValue",
                        "totolAccumulatedDepreciation",
                        "totolOriginalNetValue",
                };
                for (int i = 0; i < str1.length; i++) {
                    String s = str1[i];
                    PdfPCell cell13 = new PdfPCell(new Phrase(s, font_Zhengwen));
                    cell13.setMinimumHeight(30);
                    cell13.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell13.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    table.addCell(cell13);
                }
                for (PageData p1 : listSubliA) {
                    for (int i = 0; i < keys1.length; i++) {
                        String key = keys1[i];
                        PdfPCell cell13 = new PdfPCell(new Phrase(p1.getString(key), font_Zhengwen));
                        cell13.setMinimumHeight(30);
                        cell13.setHorizontalAlignment(Element.ALIGN_CENTER);
                        cell13.setVerticalAlignment(Element.ALIGN_MIDDLE);
                        table.addCell(cell13);
                    }
                }
            }
        } else {
            PdfPCell cell12 = new PdfPCell(new Phrase("实物资产类", font_Zhengwen));
            cell12.setMinimumHeight(30);
            cell12.setRowspan(2);
            cell12.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell12.setVerticalAlignment(Element.ALIGN_MIDDLE);
            table.addCell(cell12);
            String str1[] = {
                    "账面原值总额",
                    "累计折旧总额",
                    "账面净值总额",
            };
            String keys1[] = {
                    "totolOriginalBookValue",
                    "totolAccumulatedDepreciation",
                    "totolOriginalNetValue",
            };
            for (int i = 0; i < str1.length; i++) {
                String s = str1[i];
                PdfPCell cell13 = new PdfPCell(new Phrase(s, font_Zhengwen));
                cell13.setMinimumHeight(30);
                cell13.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell13.setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cell13);
            }
            for (int i = 0; i < keys1.length; i++) {
                PdfPCell cell13 = new PdfPCell(new Phrase("0", font_Zhengwen));
                cell13.setMinimumHeight(30);
                cell13.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell13.setVerticalAlignment(Element.ALIGN_MIDDLE);
                table.addCell(cell13);
            }
        }


        PdfPCell cell15 = new PdfPCell(new Phrase("备案资料目录", font_Zhengwen));
        cell15.setMinimumHeight(30);
        cell15.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell15.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell15.setPaddingBottom(5);
        cell15.setPaddingTop(5);
        table.addCell(cell15);

        PdfPCell cell16 = new PdfPCell(new Phrase("1、不良资产详细情况汇总表；2、经济行为批准文件；3、不良资产财务资料； 4、不良资产认定依据及鉴证资料。", font_Zhengwen));
        cell16.setColspan(3);
        cell16.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell16.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell16.setPaddingBottom(5);
        cell16.setPaddingTop(5);
        table.addCell(cell16);

        PdfPTable table2 = new PdfPTable(3);// 建立一个pdf表格
        PdfPCell cell19 = new PdfPCell(new Phrase("\n意\n\n\n" +
                "见\n\n\n" +
                "及\n\n\n" +
                "签\n\n\n" +
                "章\n\n\n", font_Zhengwen));
        cell19.setMinimumHeight(80);
        cell19.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell19.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table2.addCell(cell19);


        PdfPCell cell20 = new PdfPCell(new Phrase("填报单位意见\n\n\n\n\n\n负责人签字：\n" +
                "       （盖章）\n\n\n\n\n\n\n                                      年      月       日", font_Zhengwen));
        cell20.setMinimumHeight(40);
        cell20.setHorizontalAlignment(Element.ALIGN_LEFT);
        table2.addCell(cell20);

        PdfPCell cell21 = new PdfPCell(new Phrase("国资监管部门意见\n\n\n\n\n\n负责人签字：\n" +
                "       （盖章）\n\n\n\n\n\n\n                                      年      月       日", font_Zhengwen));
        cell21.setMinimumHeight(40);
        cell21.setHorizontalAlignment(Element.ALIGN_LEFT);
        table2.addCell(cell21);


        document.add(table);
        document.add(table2);
        document.close();
        return pdffile;
    }

    public File buildword(String id, HttpServletResponse response) throws Exception {
        PageData pd = nPLCancelRecordDao.findById(id);
        List<PageData> listSubliA = nPLCancelRecordSubliADao.findById(id);
        List<PageData> listSubliB = nPLCancelRecordSubliBDao.findById(id);
        List<PageData> listSubliC = nPLCancelRecordSubliCDao.findById(id);
        File file = null;
        try {
            if (pd != null) {
                Map<String, Object> data = new HashMap<>(16);
                data.put("recordCode", pd.getString("recordCode"));
                data.put("reportCompanyName", pd.getString("reportCompanyName"));
                String cancelType = pd.getString("cancelType");
                cancelType = baseInfoDao.findbycode(cancelType).getString("name");
                data.put("cancelType", cancelType);
                data.put("institutions", pd.getString("institutions"));
                String approvalDate = pd.getString("approvalDate");
                data.put("approvalDate", Tools.date2Str(Tools.str2Date(approvalDate), "yyyy-MM-dd"));
                data.put("cancelNote", pd.getString("cancelNote"));

                String currency = pd.getString("currency");
                currency = baseInfoDao.findbycode(currency).getString("name");
                String amount = pd.getString("amount");
                data.put("name", currency + ":" + amount);

                //审批完的时间
                if (pd.getString("status").equals("3")) {
                    List<WfCompletedTask> wfCompletedTasks = wfCompletedTaskMapper.selectByFormId(id);
                    if (CollectionUtils.isNotEmpty(wfCompletedTasks)) {
                        Optional<WfCompletedTask> max = wfCompletedTasks.stream().max(Comparator.comparing(WfCompletedTask::getFinishTime));
                        WfCompletedTask wfCompletedTask = max.get();
                        data.put("finishTime", wfCompletedTask.getFinishTime());
                        PageData pageData = userDao.findbyid(wfCompletedTask.getAssigneeId());
                        data.put("applicantName", pageData.getString("name"));
                    }
                }


                PageData pageData = new PageData();
                pageData.put("totolOriginalBookValue", "");
                pageData.put("totolAccumulatedDepreciation", "");
                pageData.put("totolOriginalNetValue", "");
                pageData.put("totolBadDebtLosses", "");
                pageData.put("recoverTheAmount", "");
                pageData.put("totolInvestmentLoss", "");

                if (CollectionUtils.isNotEmpty(listSubliA)) {
                    data.put("listSubliA", listSubliA);
                } else {
                    data.put("listSubliA", pageData);
                }

                if (CollectionUtils.isNotEmpty(listSubliB)) {
                    data.put("listSubliB", listSubliB);
                } else {
                    data.put("listSubliB", pageData);
                }

                if (CollectionUtils.isNotEmpty(listSubliC)) {
                    data.put("listSubliC", listSubliC);
                } else {
                    data.put("listSubliC", pageData);
                }

                String realPath = environment.getProperty("doc.path") + id + ".doc";

                //备案编号
                String filingId = pd.getString("recordCode");
                if (filingId == null) {
                    file = WordUtil.generateWord(data, realPath, "NPLCancelRecord.doc", "NPLCancelRecord.ftl");
                    response.setHeader("Content-Disposition", "attachment;fileName=" + file.getName());
                } else {
                    file = WordUtil.generateWord(data, realPath, filingId + ".doc", "NPLCancelRecord.ftl");
                    String fileName = new String(file.getName().getBytes("GB2312"), "ISO_8859_1");
                    response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
                }
                InputStream inputStream = new FileInputStream(file);
                // 激活下载操作
                OutputStream os = response.getOutputStream();
                // 循环写入输出流
                byte[] b = new byte[2048];
                int length;
                while ((length = inputStream.read(b)) > 0) {
                    os.write(b, 0, length);
                }
                // 这里主要关闭。
                os.close();
                inputStream.close();
            }

        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return file;
    }

    /**
     * 接收数字宁波项目信息
     *
     * @param
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public String saveNPLCancelRecordReform(String data) {
        YthResult ythResult = new YthResult();
        //成功的id集合
        List<String> successIds = new ArrayList<>();
        //失败的id集合
        List<String> failIds = new ArrayList<>();
        //失败的原因
        List<String> failReasons = new ArrayList<>();
        //将json字符串转换成list
        List<CqzcNplcancelrecord> dataList = JSON.parseArray(data, CqzcNplcancelrecord.class);
        //判断list是否为空
        if (CollectionUtil.isNotEmpty(dataList)) {
            //根据datasourceIds 查询出所有的数据
            List<CqzcNplcancelrecord> list = nplcancelrecordMapper.selectList(new LambdaQueryWrapper<CqzcNplcancelrecord>()
                    .in(CqzcNplcancelrecord::getDataSourceId, dataList.stream()
                            .map(CqzcNplcancelrecord::getDataSourceId).toArray()));
            //如果数据库中有数据，就更新，没有就新增
            for (CqzcNplcancelrecord entity : dataList) {
                String dataSourceId = entity.getDataSourceId();
                if (CollectionUtil.isNotEmpty(list)) {
                    List<String> olIds = list.stream().map(CqzcNplcancelrecord::getDataSourceId).collect(Collectors.toList());
                    //判断数据库中是否有数据
                    if (olIds.contains(dataSourceId)) {
                        for (CqzcNplcancelrecord oldEntity : list) {
                            if (dataSourceId.equals(oldEntity.getDataSourceId())) {
                                successIds.add(dataSourceId);
                                entity.setId(oldEntity.getId());
                                entity.setDataSource(YthConstant.DATA_NINGBO);
                                extracted(entity);
                                save(entity);
                                list.remove(oldEntity);
                                break;
                            }
                        }
                    } else {
                        //如果数据库中没有数据，就新增
                        entity.setDataSource(YthConstant.DATA_NINGBO);
                        extracted(entity);
                        save(entity);
                        successIds.add(entity.getDataSourceId());
                    }
                } else {
                    entity.setDataSource(YthConstant.DATA_NINGBO);
                    extracted(entity);
                    save(entity);
                    successIds.add(entity.getDataSourceId());
                }
            }
        } else {
            failReasons.add("数据为空");
        }
        ythResult.setSuccessIds(successIds);
        ythResult.setFailIds(failIds);
        ythResult.setFailReason(StringUtils.join(failReasons, ";"));
        //ythResult转换成json字符串
        return JSON.toJSONString(ythResult);
    }

    /**
     * 将数字宁波过来的数据人员id，
     *
     * @param entity
     */
    private void extracted(CqzcNplcancelrecord entity) {
        Map<String, String> orgSourceIds = orgService.getSourceId();
        Map<String, String> userSourceIds = userService.getSourceId();

        String orgId = orgSourceIds.get(entity.getOrgId());

        String createUser = userSourceIds.get(entity.getCreateUser());
        if (StringUtils.isNotBlank(orgId)) {
            entity.setOrgId(orgId);
            entity.setCreateCompanyId(orgId);
            entity.setReportCompanyId(orgId);
        }
        //资产核销企业名称 产权树
        String propertyId = propertyService.findByOrgCode(entity.getCancelCompanyName());
        if (StringUtil.isNotBlank(propertyId)) {
            entity.setCancelCompanyName(propertyId);
        }
        if (StringUtils.isNotBlank(createUser)) {
            entity.setCreateUser(createUser);
            entity.setUpdateUser(createUser);
        }
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        //A
        if (CollectionUtil.isNotEmpty(entity.getListSubliA())) {
            entity.getListSubliA().forEach(item -> {
                if (StringUtils.isNotBlank(orgId)) {
                    item.setCreateCompanyId(orgId);
                }
            });
        }
        //B
        if (CollectionUtil.isNotEmpty(entity.getListSubliB())) {
            entity.getListSubliB().forEach(item -> {
                if (StringUtils.isNotBlank(orgId)) {
                    item.setCreateCompanyId(orgId);
                }
            });
        }
        //C
        if (CollectionUtil.isNotEmpty(entity.getListSubliC())) {
            entity.getListSubliC().forEach(item -> {
                if (StringUtils.isNotBlank(orgId)) {
                    item.setCreateCompanyId(orgId);
                }
            });
        }

    }
}
